<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];


    public function getAvatar()
    {
        return url("avatars/1.webp");
    }


    protected static function boot()
    {
        parent::boot(); // TODO: Change the autogenerated stub

        static::created(function ($user) {
            $tempEmail = TempEmail::query()->where('user_id', $user->id)->first();
            $code = Str::random(10);

            if ($tempEmail == null) {
                TempEmail::query()->create([
                    "user_id" => $user->id,
                    "code" => $code
                ]);
            } else {
                $tempEmail->code = $code;
                $tempEmail->save();
            }

        });
    }


    public function posts() {
        return $this->hasMany(Post::class,'user_id','id');
    }

    public function getPosts()
    {

        $user_ids = $this->fanings->pluck('id')->toArray();
        $user_ids[] = $this->id;


        return Post::query()->whereIn('user_id',$user_ids)->with('user')->orderBy('created_at','desc')->paginate(8);
    }


    //查询所有粉丝
    public function fans()
    {
        return $this->belongsToMany(User::class,'fans','user_id','fan_id')->withTimestamps()->orderBy('fans.created_at','desc');
    }

    //查询所有的关注
    public function fanings()
    {
        return $this->belongsToMany(User::class,'fans','fan_id','user_id')->withTimestamps()->orderBy('fans.created_at','desc');
    }

    //关注某人
    public function fan($user_ids)
    {
        if (!is_array($user_ids)) {
            $user_ids = compact('user_ids');
        }
        return $this->fanings()->sync($user_ids,false);
    }

    //取消关注某人
    public function unfan($user_ids)
    {

        if (!is_array($user_ids)) {
            $user_ids = compact('user_ids');
        }

        return $this->fanings()->detach($user_ids,false);
    }

    //判断某人是否关注某人
    public function isFaning($user_id)
    {
        return $this->fanings()->get()->contains($user_id);
    }
}
